package com.fjec.paid.service.impl;

import com.fjec.common.exception.BizException;
import com.fjec.common.shiro.AccountInfo;
import com.fjec.common.util.DateUtil;
import com.fjec.common.util.JsonUtil;
import com.fjec.common.util.SequenceIdGenerator;
import com.fjec.common.ys.PaidHelper;
import com.fjec.common.ys.YsProperties;
import com.fjec.common.ys.protocol.ResponsePaid;
import com.fjec.paid.entity.BizOrderPayment;
import com.fjec.paid.entity.BizWechatPayment;
import com.fjec.paid.entity.BizYsPayment;
import com.fjec.paid.entity.RefOrderPayment;
import com.fjec.paid.feign.MarketClient;
import com.fjec.paid.rabbitmq.provider.YsPayDelayQueryProvoder;
import com.fjec.paid.service.*;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import org.apache.commons.collections.MapUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Map;

@Service
public class PhysicalPreparePayServiceImpl implements PhysicalPreparePayService {

    @Autowired
    private PaidHelper paidHelper;

    @Resource
    private IBizOrderPaymentService bizOrderPaymentService;

    @Resource
    private IBizYsPaymentService bizYsPaymentService;

    @Resource
    private IRefOrderPaymentService refOrderPaymentService;

    @Autowired
    private SequenceIdGenerator idGenerator;

    @Autowired
    private MarketClient marketClient;

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public void handle(String subOpenId, String outTradeNo, String shopDate, String subject, String totalAmount,
                       String sellerId, String sellerName, BizOrderPayment bizOrderPayment, Integer paymentType) throws Exception {

        // 调用银盛预支付接口，获取 jsapi info
        Map<String, Object> resMap = paidHelper.wxPreparePaid(subOpenId, outTradeNo, shopDate, subject, totalAmount, sellerId, sellerName, paymentType);
        if (resMap == null)
            return;
        String code = MapUtils.getString(resMap, "code");
        String msg = MapUtils.getString(resMap, "msg");
        String tradeStatus = MapUtils.getString(resMap, "trade_status");
        if (!code.equals("10000") || !msg.equals("Success") || !tradeStatus.equals("WAIT_BUYER_PAY"))
            return;

        String tradeNo = MapUtils.getString(resMap, "trade_no");
        // 得到jsapi info，更新订单支付表 支付状态
        bizOrderPayment.setPaymentStatus(1);
        bizOrderPaymentService.updateById(bizOrderPayment);

        LocalDateTime now = DateUtil.nowLdt();
        // 银盛订单支付表
        BizYsPayment bizYsPayment = new BizYsPayment();
        bizYsPayment.setId(idGenerator.nextId());
        bizYsPayment.setPaymentId(bizOrderPayment.getId());
        bizYsPayment.setOutTradeNo(outTradeNo);
        bizYsPayment.setShopdate(shopDate);
        bizYsPayment.setSubject(subject);
        bizYsPayment.setTotalAmount(bizOrderPayment.getAmount());
        bizYsPayment.setCurrency("CNY");
        bizYsPayment.setTimeoutExpress("2d");
        bizYsPayment.setSubOpenid(subOpenId);
        bizYsPayment.setIsMinipg(1);
        bizYsPayment.setPaidType(1);
        bizYsPayment.setTradeNo(tradeNo);
        bizYsPayment.setTradeStatus(tradeStatus);
        bizYsPayment.setPaidStatus(1);
        bizYsPayment.setDelFlag(0);
        bizYsPayment.setYsResponse(JsonUtil.toJson(resMap));
        bizYsPayment.setCreateTime(now);
        bizYsPaymentService.save(bizYsPayment);

        // 订单支付关联表
        RefOrderPayment refOrderPayment = new RefOrderPayment();
        String orderId = outTradeNo.substring(8);
        refOrderPayment.setId(Long.valueOf(orderId));
        refOrderPayment.setOrderPayId(bizOrderPayment.getId());
        refOrderPayment.setAmount(bizOrderPayment.getAmount());
        refOrderPayment.setSyncOrder(0);
        refOrderPayment.setCreateTime(now);
        refOrderPaymentService.save(refOrderPayment);

    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public Map<String, Object> getPreparePayPackage(Long orderId) {
        Map<String, Object> result = bizOrderPaymentService.getPreparePayPackage(orderId);
        if (result == null || MapUtils.isEmpty(result))
            return null;
        String jsapiPayInfo = MapUtils.getString(result, "ysResponse");
        ResponsePaid responsePaid = JsonUtil.jsonToObject(jsapiPayInfo, ResponsePaid.class);
        Map<String, Object> data = JsonUtil.jsonToMap(responsePaid.getJsapi_pay_info());
        // 如果是支付验证，则 rpc market服务设置进件状态为完全成功6
        Integer paymentType = MapUtils.getInteger(result, "paymentType");
        if (data != null && paymentType == 3) {
            int success = marketClient.setSelfPaySuccessfully(orderId);
            if (success != 0)
                throw new BizException(null, "getPreparePayPackage.setSelfPaySuccessfully error");
        }

        result.put("ysResponse", data);
        return result;
    }
}
